/*
 * 文件名：DownloadPictureThread.java
 * 版权：Copyright by 联通系统集成有限公司
 * 描述：
 * 修改人：admin
 * 修改时间：2018年10月16日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.bicycle.wxpublic.handle;

import com.bicycle.service.entity.BicycleCommonFile;
import com.bicycle.service.entity.BicycleSequenceReportPhoto;
import com.bicycle.service.mapper.BicycleCommonFileMapper;
import com.bicycle.service.mapper.BicycleSequenceReportPhotoMapper;
import com.bicycle.wxpublic.service.WeChatService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Date;

public class DownloadPictureThread extends Thread {
    private static final Logger LOGGER = LoggerFactory.getLogger(DownloadPictureThread.class);

    // 处理前的图片
    private String[] preMediaId;
    // 处理后的图片
    private String[] afterMediaId;
    // 举报的图片
    private String[] reportMediaId;

    private BicycleSequenceReportPhotoMapper reportPhotoMapper;

    private Integer detailId;

    private Integer processId;

    private BicycleCommonFileMapper fileMapper;

    private WeChatService weChatService;

    private String uploadPath;

    private String downloadPath;

    private Environment environment;

    public DownloadPictureThread() {

    }

    public DownloadPictureThread(String[] preMediaId, String[] afterMediaId, String[] reportMediaId, BicycleSequenceReportPhotoMapper reportPhotoMapper, Integer detailId, Integer processId, BicycleCommonFileMapper fileMapper, WeChatService weChatService, String uploadPath, String downloadPath, Environment environment) {
        this.preMediaId = preMediaId;
        this.afterMediaId = afterMediaId;
        this.reportMediaId = reportMediaId;
        this.reportPhotoMapper = reportPhotoMapper;
        this.detailId = detailId;
        this.processId = processId;
        this.fileMapper = fileMapper;
        this.weChatService = weChatService;
        this.uploadPath = uploadPath;
        this.downloadPath = downloadPath;
        this.environment = environment;
    }

    @Override
    public void run() {
        LOGGER.warn(">>>>>>>>>> DownloadPictureThread 处理图片开始...");
        if (preMediaId != null) {
            // 处理前的照片
            LOGGER.warn(">>>>>>>>>> DownloadPictureThread 处理前的图片一共{}条", preMediaId.length);
            for (int i = 0; i < preMediaId.length; i++) {
                if (StringUtils.isNotBlank(preMediaId[i])) {
                    LOGGER.warn(">>>>>>>>>> DownloadPictureThread 处理前的图片正在下载,preMediaId:{},当前第{}张...", preMediaId[i], (i + 1));
                    BicycleSequenceReportPhoto reportDetailPhoto = new BicycleSequenceReportPhoto();
                    reportDetailPhoto.setPhotoType(2);// 处理前的照片
                    reportDetailPhoto.setFileId(saveImage(preMediaId[i]));
                    reportDetailPhoto.setDetailId(detailId);
                    reportDetailPhoto.setCreateTime(new Date());
                    reportDetailPhoto.setProcessId(processId);
                    reportDetailPhoto.setMediaId(preMediaId[i]);
                    reportPhotoMapper.insert(reportDetailPhoto);
                    LOGGER.warn(">>>>>>>>>> DownloadPictureThread 处理前的图片下载完成,preMediaId:{},当前第{}张...", preMediaId[i], (i + 1));
                }
            }
        }
        if (afterMediaId != null) {
            LOGGER.warn(">>>>>>>>>> DownloadPictureThread 处理后的图片一共{}条", afterMediaId.length);
            // 处理后照片
            for (int i = 0; i < afterMediaId.length; i++) {
                if (StringUtils.isNotBlank(afterMediaId[i])) {
                    LOGGER.warn(">>>>>>>>>> DownloadPictureThread 处理后的图片正在下载,afterMediaId:{},当前第{}张...", afterMediaId[i], (i + 1));
                    BicycleSequenceReportPhoto reportDetailPhoto = new BicycleSequenceReportPhoto();
                    reportDetailPhoto.setPhotoType(3);// 处理后的照片
                    reportDetailPhoto.setFileId(saveImage(afterMediaId[i]));
                    reportDetailPhoto.setDetailId(detailId);
                    reportDetailPhoto.setCreateTime(new Date());
                    reportDetailPhoto.setProcessId(processId);
                    reportDetailPhoto.setMediaId(afterMediaId[i]);
                    reportPhotoMapper.insert(reportDetailPhoto);
                    LOGGER.warn(">>>>>>>>>> DownloadPictureThread 处理后的图片下载完成,afterMediaId:{},当前第{}张...", afterMediaId[i], (i + 1));
                }
            }
        }
        if (reportMediaId != null) {
            LOGGER.warn(">>>>>>>>>> DownloadPictureThread 举报的图片一共{}条", reportMediaId.length);
            // 举报照片
            for (int i = 0; i < reportMediaId.length; i++) {
                if (StringUtils.isNotBlank(reportMediaId[i])) {
                    LOGGER.warn(">>>>>>>>>> DownloadPictureThread 举报的图片正在下载,reportMediaId:{},当前第{}张...", reportMediaId[i], (i + 1));
                    BicycleSequenceReportPhoto reportDetailPhoto = new BicycleSequenceReportPhoto();
                    reportDetailPhoto.setPhotoType(1);// 举报照片
                    reportDetailPhoto.setFileId(saveImage(reportMediaId[i]));
                    reportDetailPhoto.setDetailId(detailId);
                    reportDetailPhoto.setMediaId(reportMediaId[i]);
                    reportDetailPhoto.setCreateTime(new Date());
                    reportPhotoMapper.insert(reportDetailPhoto);
                    LOGGER.warn(">>>>>>>>>> DownloadPictureThread 举报的图片下载完成,reportMediaId:{},当前第{}张...", reportMediaId[i], (i + 1));
                }
            }
        }

        LOGGER.warn(">>>>>>>>>> DownloadPictureThread 处理图片结束...");
    }

    private Integer saveImage(String mediaId) {
        // 获取微信图片地址
        String wxImageUrl = MessageFormat.format(environment.getProperty("wxpublic.wx.url.image"),
                weChatService.jsapiSignature().getAccessToken(), mediaId);
        FileOutputStream outStream = null;
        try {
            LOGGER.warn(">>>>>>>>>> 获取微信图片地址:{}", wxImageUrl);
            URL url = new URL(wxImageUrl);
            // 打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求方式为"GET"
            conn.setRequestMethod("GET");
            // 超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
            // 通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();

            String date = DateFormatUtils.format(new Date(), "yyyyMMdd");
            BicycleCommonFile commonFile = new BicycleCommonFile();
            commonFile.setCreateTime(new Date());
            // 定义文件保存路径
            File saveFile = new File(uploadPath + File.separator + date + File.separator);
            // 如果文件地址为空时创建路径
            if (!saveFile.exists()) {
                saveFile.mkdirs();
            }
            // 获取文件的后缀
            String suffix = getFileexpandedName(conn.getHeaderField("Content-Type"));
            if (StringUtils.isBlank(suffix)) {
                return null;
            }
            commonFile.setFileSuffix(suffix);
            // 文件名称由时间构成
            String name = String.valueOf(System.currentTimeMillis());
            commonFile.setFileName(name);
            commonFile.setRelativePath(File.separator + date + File.separator + commonFile.getFileName() + commonFile.getFileSuffix());
            commonFile.setDownloadPath(downloadPath);
            commonFile.setAbsolutePath(uploadPath);
            // 构件完整文件路径名称
            String pathname = uploadPath + commonFile.getRelativePath();
            // 得到图片的二进制数据，以二进制封装得到数据，具有通用性
            byte[] data = readInputStream(inStream);
            commonFile.setFileSize(data.length);
            // new一个文件对象用来保存图片，默认保存当前工程根目录
            File imageFile = new File(pathname);
            // 创建输出流
            outStream = new FileOutputStream(imageFile);
            // 写入数据
            outStream.write(data);
            fileMapper.insert(commonFile);
            return commonFile.getId();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outStream != null) {
                try {
                    // 关闭输出流
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    /**
     * 根据内容类型判断文件扩展名
     *
     * @param contentType 内容类型
     * @return
     */
    public String getFileexpandedName(String contentType) {
        String fileEndWitsh = "";
        if ("image/jpeg".equals(contentType))
            fileEndWitsh = ".jpg";
        else if ("audio/mpeg".equals(contentType))
            fileEndWitsh = ".mp3";
        else if ("audio/amr".equals(contentType))
            fileEndWitsh = ".amr";
        else if ("video/mp4".equals(contentType))
            fileEndWitsh = ".mp4";
        else if ("video/mpeg4".equals(contentType))
            fileEndWitsh = ".mp4";
        return fileEndWitsh;
    }

}
